package fun.sssdnsy.controller;

import fun.sssdnsy.model.RichContent;
import fun.sssdnsy.util.*;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.*;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 主控制器
 * 处理富文本编辑、智能保存、人脸识别等功能
 */
public class MainController implements Initializable {

    @FXML
    private RichTextEditor richTextEditor;
    @FXML
    private Label lblStatus;

    private static final transient Logger log = LoggerFactory.getLogger(MainController.class);
    private Stage primaryStage;
    private boolean isModified = false;
    private final File encryptedFile = new File("data.mypwd");

    /**
     * 初始化 Controller
     */
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        richTextEditor.setWrapText(true);
        VBox.setVgrow(richTextEditor, javafx.scene.layout.Priority.ALWAYS);
        applySettings();
        loadEncryptedData();
        setupClipboardPaste();
        applyInitialStyles();
    }


    /**
     * 初始化应用（手动调用）
     */
    public void initializeApp(Stage stage) {
        this.primaryStage = stage;
        Scene scene = stage.getScene();
        setupAutoSave();
        richTextEditor.setSaveHandler(() -> saveEncryptedData());
    }



    private void applyInitialStyles() {
        richTextEditor.setStyle(
                "-fx-padding: 10;" +
                        "-fx-background-color: white;" +
                        "-fx-border-color: #ddd;" +
                        "-fx-border-width: 1;"
        );
    }

    /**
     * 添加剪贴板图片粘贴支持
     */
    private void setupClipboardPaste() {
        richTextEditor.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
            if (e.isControlDown() && e.getCode() == KeyCode.V) {
                Clipboard clipboard = Clipboard.getSystemClipboard();
                if (clipboard.hasImage()) {
                    Image image = clipboard.getImage();
                    richTextEditor.insertImage(richTextEditor.getCaretPosition(), image);
                    e.consume();
                }
            }
        });
    }


    /**
     * 监听用户输入，标记内容已修改
     */
    @FXML
    private void onTextChanged() {
        isModified = true;
        if (isModified) {
            lblStatus.setText(I18nUtil.getString("status.typing"));
        }
        isModified = false;
    }


    /**
     * 载入加密数据（支持图文）
     */
    private void loadEncryptedData() {
        if (encryptedFile.exists()) {
            String encrypted = CryptoUtil.decryptFile(encryptedFile);
            RichContent content = parseRichContent(encrypted);

            richTextEditor.clear();
            richTextEditor.appendText(content.getText());

            for (RichContent.ImageData img : content.getImages()) {
                Image image = decodeBase64Image(img.getBase64());
                richTextEditor.insertImage(img.getPosition(), image);
                adjustImageSize(img.getPosition(), img.getWidth());
            }
        }
    }

    /**
     * 保存加密数据（支持图文）
     */
    private void saveEncryptedData() {
//        if (isModified && FaceRecognitionUtil.verifyUser()) {
        if (isModified) {
            log.info("Ctrl+S");
            RichContent content = new RichContent();
            content.setText(richTextEditor.getText());
            content.setImages(extractImagesFromEditor());

            String json = JsonUtil.toJson(content);
            CryptoUtil.encryptToFile(json, encryptedFile);
            isModified = false;
        }
    }

    private List<RichContent.ImageData> extractImagesFromEditor() {
        return null;
//                richTextEditor.getParagraphs().stream()
//                .flatMap(para -> para.getNodeElements().stream()
//                        .filter(e -> e.getNode() instanceof ImageView)
//                        .map(e -> {
//                            ImageView iv = (ImageView) e.getNode();
//                            RichContent.ImageData imgData = new RichContent.ImageData();
//
//                            // 使用正确的getter方法获取位置
//                            imgData.setPosition(e.getStart()); // 或 e.getStartPosition()
//                            imgData.setBase64(encodeToBase64(iv.getImage()));
//                            imgData.setWidth(iv.getFitWidth());
//
//                            return imgData;
//                        }))
//                .collect(Collectors.toList());
    }

    private String encodeToBase64(Image image) throws IOException {
        BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bImage, "png", os);
        return Base64.getEncoder().encodeToString(os.toByteArray());
    }

    private RichContent parseRichContent(String encrypted) {
        return JsonUtil.fromJson(encrypted, RichContent.class);
    }

    private Image decodeBase64Image(String base64) {
        byte[] data = Base64.getDecoder().decode(base64);
        return new Image(new ByteArrayInputStream(data));
    }

    private void adjustImageSize(int position, double width) {
        Node node = richTextEditor.getNode(position);
        if (node instanceof ImageView) {
            ImageView iv = (ImageView) node;
            iv.setFitWidth(width);
            iv.setPreserveRatio(true);
        }
    }

    /**
     * 设置自动保存
     */
    private void setupAutoSave() {
        if (primaryStage != null) {
            primaryStage.setOnCloseRequest(event -> saveEncryptedData());
        }
    }

    /**
     * 应用用户设置
     */
    private void applySettings() {
        if (lblStatus != null) {
            I18nUtil.applyI18n(lblStatus, "status.ready");
        }
        String theme = ConfigUtil.get("theme", "light");
        applyTheme(theme);
    }

    /**
     * 切换主题
     */
    private void applyTheme(String theme) {
//        if (mainContainer != null) {
//            String styleClass = theme.equals("dark") ? "dark-theme" : "light-theme";
//            mainContainer.getStyleClass().setAll(styleClass);
//        } else {
//            log.error("[错误] mainContainer 为空，无法应用主题。");
//        }
    }

    /**
     * 切换文本样式（加粗、斜体、下划线）
     */
    private void toggleTextStyle(String symbol) {
        String selectedText = richTextEditor.getSelectedText();
        if (!selectedText.isEmpty()) {
            String newText = symbol + selectedText + symbol;
            richTextEditor.replaceSelection(newText);
        }
    }

    /**
     * 打开设置窗口
     */
    @FXML
    private void onOpenSettings() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fun/sssdnsy/view/SettingsView.fxml"));
            loader.setResources(I18nUtil.bundle);
            Parent root = loader.load();

            SettingsController controller = loader.getController();
            Stage settingsStage = new Stage();
            controller.setStage(settingsStage); // 传递Stage
            // 监听窗口关闭事件以刷新主界面
            settingsStage.setOnHidden(e -> applySettings());

            settingsStage.setTitle(I18nUtil.getString("settings.title"));
            settingsStage.initModality(Modality.APPLICATION_MODAL);
            settingsStage.initOwner(primaryStage);
            settingsStage.setScene(new Scene(root));
            settingsStage.setResizable(false);
            settingsStage.show();

        } catch (IOException e) {
            e.printStackTrace();
            AlertUtil.showError("无法打开设置窗口: " + e.getMessage());
        }
    }

    // 文件操作
    @FXML
    private void onNewFile(ActionEvent actionEvent) {
        richTextEditor.clear();
        isModified = false;
    }

    @FXML
    private void onOpenFile(ActionEvent actionEvent) {
        FileChooser fileChooser = new FileChooser();
        extracted(fileChooser);
        File file = fileChooser.showOpenDialog(primaryStage);
        if (file != null) {
            try {
                String content = Files.readString(file.toPath());
                richTextEditor.setText(content);
            } catch (IOException e) {
                log.error("[错误] 无法读取文件: " + e.getMessage());
            }
        }
    }

    @FXML
    private void onSaveFile(ActionEvent actionEvent) {
        FileChooser fileChooser = new FileChooser();
        extracted(fileChooser);
        File file = fileChooser.showSaveDialog(primaryStage);
        if (file != null) {
            try {
                Files.writeString(file.toPath(), richTextEditor.getText(), StandardOpenOption.CREATE);
            } catch (IOException e) {
                log.error("[错误] 无法保存文件: " + e.getMessage());
            }
        }
    }

    private static void extracted(FileChooser fileChooser) {
        // 设置默认文件名
        fileChooser.setInitialFileName(generateDefaultFilename());

        // 设置文件过滤器（仅允许保存为 .mypwd）
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
                "MyPwd Files (*.mypwd)", "*.mypwd"
        );
        fileChooser.getExtensionFilters().add(extFilter);
    }


    /**
     * 生成默认文件名：yyyymmddhhmmss.mypwd
     */
    public static String generateDefaultFilename() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        return formatter.format(now) + ".mypwd";
    }

    @FXML
    private void onExit(ActionEvent actionEvent) {
        primaryStage.close();
    }

    // 关于
    @FXML
    private void onAbout(ActionEvent actionEvent) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("关于");
        alert.setHeaderText("MyPwd 应用");
        alert.setContentText("版本 1.0\n作者: sssdnsy\n安全存储与编辑工具");
        alert.showAndWait();
    }

    @FXML
    private void onUndo(ActionEvent actionEvent) {
        richTextEditor.undo();
    }

    // 重做
    @FXML
    private void onRedo(ActionEvent actionEvent) {
        richTextEditor.redo();
    }

    // 剪切
    @FXML
    private void onCut(ActionEvent actionEvent) {
        richTextEditor.cut();
    }

    // 复制
    @FXML
    private void onCopy(ActionEvent actionEvent) {
        richTextEditor.copy();
    }

    // 粘贴
    @FXML
    private void onPaste(ActionEvent actionEvent) {
        richTextEditor.paste();
    }

    @FXML
    private void onBold(ActionEvent actionEvent) {
        toggleTextStyle("**");
    }

    @FXML
    private void onItalic(ActionEvent actionEvent) {
        toggleTextStyle("*");
    }

    @FXML
    private void onUnderline(ActionEvent actionEvent) {
        toggleTextStyle("__");
    }


}
